package com.atguigu.gmallre.mock.stage;


import com.atguigu.gmallre.mock.bean.*;
import com.atguigu.gmallre.mock.config.AppConfig;
import com.atguigu.gmallre.mock.constant.GmallConstant;
import com.atguigu.gmallre.mock.factory.UserSession;
import com.atguigu.gmallre.mock.log.*;
import com.atguigu.gmallre.mock.log.enums.ActionId;
import com.atguigu.gmallre.mock.log.enums.ItemType;
import com.atguigu.gmallre.mock.log.enums.PageId;
import com.atguigu.gmallre.mock.service.*;
import com.atguigu.mock.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("goodDetail")
public class GoodDetailStage implements Stage {

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    LogService logService;

    @Autowired
    LoginStage loginStage;

    @Override
    public boolean handle() {


        List<AppDisplay> appDisplayList = UserSession.getLastDisplayThreadLocal() ;
        Long skuId=null;
        Integer fromPosId;
        Integer fromPosSeq;
        if(appDisplayList==null ||appDisplayList.size()==0){
              skuId = AppDisplay.builder().getSkuIdByUser(UserSession.getUserInfo());
              fromPosId=999;
              fromPosSeq=999;
        }else{
            AppDisplay appDisplay = RandomCollection.getOneFrom(appDisplayList);
             skuId=Long.valueOf(appDisplay.getItem()) ;
            fromPosId=appDisplay.getPos_id();
            fromPosSeq=appDisplay.getPos_seq();
        }





        SkuInfo skuInfo  = skuInfoService.getById(skuId , true);

        AppMain appMain =  mainLog(skuInfo.getId()+"",fromPosId,fromPosSeq);

        handleFavor(appMain,skuInfo );

        tryBuySku(appMain,skuInfo);

        logService.doLog(appMain) ;

        UserSession.setLastPageId(PageId.good_detail);
        UserSession.setCurSkuInfo(skuInfo );
        return true;
    }



    @Autowired
    CartInfoService cartInfoService;

    @Autowired
    FavorInfoService favorInfoService;

    @Autowired
    CommentInfoService commentInfoService;

    private SkuInfo getSkuInfoByPurpose(){
            Map<Long, SkuInfo> skuInfoMap = skuInfoService.all(true);
            SkuInfo skuInfo=null;
            if(skuInfoMap.size()!=0){
                skuInfo = RandomCollection.getOneFrom(skuInfoMap );
            }
            return  skuInfo;
    }






    private  AppMain mainLog(String skuId,Integer fromPosId,Integer fromPosSeq){
        AppCommon appCommon = UserSession.getAppCommon();


        Integer durTime= RandomNum.getRandInt(5000, AppConfig.page_during_max_ms);

        AppPage appPage = AppPage.builder()
                .last_page_id(UserSession.getLastPageId())
                .from_pos_id(fromPosId )
                .from_pos_seq(fromPosSeq)
                .item(skuId )
                .item_type(ItemType.sku_id)
                .during_time(durTime)
                .page_id(PageId.good_detail).buildFinal();
        List<AppDisplay> appDisplayList = AppDisplay.builder().pos_id(4).max_size(9).buildList();
        UserSession.setLastDisplay(appDisplayList);
        UserSession.addTimeByDuringTime(durTime);
        AppMain appMain = AppMain.builder().common(appCommon).page(appPage).displays(appDisplayList).ts(UserSession.getCurDateTime().getTime()).checkError().build();
        return appMain;
    }


    private void   tryBuySku( AppMain appMain,SkuInfo skuInfo ){
         boolean ifCart = RandomBox.builder().add(true, AppConfig.if_cart_rate).add(false, 100 - AppConfig.if_cart_rate).build().getRandBoolValue();
         if(!ifCart){
             return;
         }
         loginStage.checkLogin(appMain);
        if(UserSession.getNextStageInfo()==null|| !UserSession.getNextStageInfo().equals(OrderStage.class)) {
            List<CartInfo> cartList = UserSession.getCartList();
            CartInfo addCartInfo=null;
            UserSession.addTimeByDuringTime(3000);
            if (cartList!=null){
                for (CartInfo cartInfo : cartList) {
                    if(cartInfo.getSkuId()==skuInfo.getId()){
                        cartInfo.setSkuNum(cartInfo.getSkuNum()+1);
                        cartInfo.setCartPrice(skuInfo.getPrice());
                        cartInfo.setOperateTime(UserSession.getCurDateTime());
                        addCartInfo=cartInfo;
                    }
                }
            }
            if(addCartInfo==null){
                addCartInfo = genCart(skuInfo);
            }
            AppAction cartAction = new AppAction(ActionId.cart_add, ItemType.sku_id, addCartInfo.getSkuId().toString());
            appMain.addAction(cartAction);

            cartInfoService.saveOrUpdate(addCartInfo,true);
        }else if( UserSession.getNextStageInfo().equals(OrderStage.class)){
            UserSession.setBuyingSkuInfo(skuInfo);
        }

    }




    //生成购物车
    public CartInfo genCart(SkuInfo skuInfo){

            CartInfo cartInfo = new CartInfo();
            cartInfo.setSkuName(skuInfo.getSkuName());
            cartInfo.setSkuNum(1L);
            cartInfo.setSkuId(skuInfo.getId());
            cartInfo.setCartPrice(skuInfo.getPrice());
            cartInfo.setUserId(UserSession.getUserInfo().getId());
            cartInfo.setCreateTime(UserSession.getCurDateTime());
            cartInfo.setIsOrdered(0);
            UserSession.addCart(cartInfo);
            return cartInfo;

    }



    // 添加收藏
    private  void   handleFavor(AppMain appMain, SkuInfo skuInfo ){
        List<FavorInfo> favorList = UserSession.getFavorList();
        FavorInfo existsFavor= existsFavorList(skuInfo.getId());




        if(existsFavor!=null){  // 点过收藏
            Boolean ifFavorCancel=  RandomBox.builder().add(true ,AppConfig.if_favor_rate)
                    .add(false,100-AppConfig.if_favor_cancel_rate).build().getRandBoolValue();
            if(ifFavorCancel){ //取消收藏
                UserSession.addTimeByDuringTime(2000);
                existsFavor.setIsCancel("0");
                favorInfoService.saveOrUpdate(existsFavor);
                AppAction favorAction = new AppAction(ActionId.favor_canel, ItemType.sku_id, existsFavor.getSkuId().toString());
                appMain.addAction(favorAction);
                favorList.remove(existsFavor);
            }

        }else{ // 没点过收藏
            Boolean ifFavor=  RandomBox.builder().add(true ,AppConfig.if_favor_rate)
                    .add(false,100-AppConfig.if_favor_rate).build().getRandBoolValue();
            if(ifFavor){  // 收藏
                boolean ifLogin = loginStage.checkLogin(appMain);
                if(!ifLogin){
                    existsFavor=  existsFavorList(  skuInfo.getId());
                    if(existsFavor!=null){
                        return;
                    }
                }

                UserSession.addTimeByDuringTime(2000);
                FavorInfo favorInfo = genFavor(skuInfo);
                favorInfoService.saveOrUpdate(favorInfo);

                AppAction favorAction = new AppAction(ActionId.favor_add, ItemType.sku_id, favorInfo.getSkuId().toString());
                appMain.addAction(favorAction);

                UserSession.addFavor(favorInfo);
            }
        }




    }

    private  FavorInfo existsFavorList(Long skuId){
        FavorInfo existsFavor= null;
        List<FavorInfo> favorList = UserSession.getFavorList();
        if(favorList!=null){
            for (FavorInfo favorInfo : favorList) {
                if(skuId==favorInfo.getId()){
                    existsFavor=favorInfo;
                    break;
                }
            }
        }

        return existsFavor;

    }


    public FavorInfo genFavor(SkuInfo skuInfo){

        FavorInfo favorInfo = new FavorInfo();

        favorInfo.setSkuId(skuInfo.getId());
        favorInfo.setSpuId(skuInfo.getSpuId());
        favorInfo.setUserId(UserSession.getUserInfo().getId());
        favorInfo.setCreateTime(UserSession.getCurDateTime());
        favorInfo.setIsCancel("0");
        return favorInfo;

    }



}
